package neuedu.mq;

import com.alibaba.fastjson.JSONObject;
import com.neuedu.mq.NeuEmail;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Component
public class WyEmailListener {
    @Value("${spring.mail.username}")
    String from;
    @Resource
    JavaMailSender javaMailSender;// 发送邮件的类
    @RabbitListener(queues = "handanqueue")
    public void emailHandler(String message) throws MessagingException {
        // 将json字符串转换为对象
        NeuEmail neuEmail = JSONObject.parseObject(message, NeuEmail.class);
        // 创建邮件
        final MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // 邮件发送的辅助类
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setTo(neuEmail.getTo());
        helper.setSubject(neuEmail.getSubject());
        helper.setText(neuEmail.getText(), true);
        helper.setFrom(from);
        javaMailSender.send(mimeMessage);
    }
}
